package com.fengyi.library.repository;

import com.fengyi.library.model.Book;
import com.fengyi.library.model.Loan;
import com.fengyi.library.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.LocalDate;
import java.util.List;

public interface LoanRepository extends JpaRepository<Loan, Integer> {
    Page<Loan> findByUser(User user, Pageable pageable);
    
    List<Loan> findByUserAndStatus(User user, Loan.LoanStatus status);
    
    List<Loan> findByBookAndStatus(Book book, Loan.LoanStatus status);
    
    @Query("SELECT l FROM Loan l WHERE l.status = 'BORROWED' AND l.dueDate < :today")
    List<Loan> findOverdueLoans(@Param("today") LocalDate today);
    
    /**
     * 查找状态为指定状态且到期日期早于指定日期的借阅
     * 用于查找已过期但仍标记为BORROWED的借阅
     */
    List<Loan> findByStatusAndDueDateBefore(Loan.LoanStatus status, LocalDate date);
    
    @Query("SELECT COUNT(l) FROM Loan l WHERE l.user = :user AND l.book = :book AND l.status = 'BORROWED'")
    long countBorrowedBooksByUser(@Param("user") User user, @Param("book") Book book);
    
    @Query("SELECT COUNT(l) FROM Loan l WHERE l.user = :user AND l.status = 'BORROWED'")
    long countCurrentBorrowedBooks(@Param("user") User user);
    
    /**
     * 根据用户名或图书标题搜索借阅记录
     * 使用JPQL查询，可以匹配用户名或图书标题中包含关键词的记录
     */
    @Query("SELECT l FROM Loan l WHERE LOWER(l.user.name) LIKE LOWER(CONCAT('%', :keyword, '%')) OR LOWER(l.book.title) LIKE LOWER(CONCAT('%', :keyword, '%'))")
    Page<Loan> searchLoans(@Param("keyword") String keyword, Pageable pageable);

    Page<Loan> findByStatus(Loan.LoanStatus status, Pageable pageable);
}
